package me.frank;

import org.apache.kafka.clients.producer.Partitioner;
import org.apache.kafka.common.Cluster;

import java.util.Map;
import java.util.Random;

/**
 * @Author Frank Wang
 * @Description:
 * @Date 2018/11/1 9:58
 */
public class MyPartition implements Partitioner {
    private Random random = new Random();
    @Override
    public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) {
        Integer count = cluster.partitionCountForTopic(topic);
        int partitionNum=0;
        if (key == null) {
            partitionNum=random.nextInt(count);
        }else {
            partitionNum=Math.abs(key.hashCode()%count);
        }
        System.out.println("key ->"+key+", value "+value+"->"+partitionNum);
        return partitionNum;
    }

    @Override
    public void close() {

    }

    @Override
    public void configure(Map<String, ?> configs) {

    }
}
